import express from "express";
import { readFileSync, writeFileSync } from "node:fs";
import moment from "moment";


const router = express.Router();
const dataFile = "service/data/tableData.json";


router.post("/save", (req, res) => {
  const data = req.body;
  let back;
  let tableData;
  try {
    tableData = readFileSync(dataFile, "utf8");
    if (tableData) {
      tableData = JSON.parse(tableData);
    } else {
      tableData = [];
    }
    if (data.id) {
      tableData.map(m => {
        if (m.id === data.id) {
          m.title = data.title;
          m.image1 = data.image1;
          m.image2 = data.image2;
          m.remark = data.remark;
          m.update_time = moment().format("YYYY-MM-DD HH:mm:ss");
        }
        return m;
      });
    } else {
      data.id = new Date().getTime();
      data.create_time = moment().format("YYYY-MM-DD HH:mm:ss");
      data.update_time = "";
      tableData.push(data);
    }
    writeFileSync(dataFile, JSON.stringify(tableData));
    back = {
      code: 20000,
      msg: "保存成功;",
      data: null
    };
  } catch (err) {
    back = {
      code: 50000,
      msg: "保存失败:" + err,
      data: null
    };
  }
  res.send(back);
});

router.post("/search", (req, res) => {
  const params = req.body;
  try {
    const text = readFileSync(dataFile, "utf8");
    let tableData;
    if (text) {
      tableData = JSON.parse(text);
    } else {
      tableData = [];
    }
    const back = [];
    tableData.forEach(line => {
      console.log(`Line from file: ${JSON.stringify(line)}`);
      if (params.title) {
        if (line.title.indexOf(params.title) > -1) {
          back.push(line);
        }
      } else {
        back.push(line);
      }
    });
    res.send({
      code: 20000,
      msg: "查询成功;",
      data: back
    });
  } catch (err) {
    res.send({
      code: 50000,
      msg: "未查询到数据",
      data: []
    });
  }

});

export default router;
